package com.cn.netbroadcast;

import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

import com.cn.demo_01.R;
import com.cn.netbroadcast.NetBroadcastReceiver.NetEventHandler;

public class MainActivity extends Activity implements NetEventHandler {
	private NetBroadcastReceiver netReceiver;
	private boolean netState = false;
	private TextView tView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		netState = NetUtil.getNetworkState(this) != 0 ? true : false;
		setContentView(R.layout.activity_main);
		
		tView = (TextView)findViewById(R.id.tv);
		
//		if (netState) {
//			tView.setText("网络连接成功");
//		}else {
//			tView.setText("网络连接失败");
//		}
		
		regist();
	}
	
	/**
	 * 注册广播
	 */
	private void regist() {
		netReceiver = new NetBroadcastReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		registerReceiver(netReceiver, filter);
		NetBroadcastReceiver.mListeners.add(this);
	}

	@Override
	public void onNetChange() {
		if (NetUtil.getNetworkState(this) == NetUtil.NETWORN_NONE) {
			netState = false;
			tView.setText("网络连接失败");
		} else {
			netState = true;
			tView.setText("网络连接成功");
		}
	}
}
